//
//  CommentVC.swift
//  mmda
//
//  Created by 李陆涛 on 2018/8/12.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift

class CommentVC: BaseVC {

    @IBOutlet weak var commentBGView: UIView!
    
    @IBOutlet weak var commetTF: IQTextView!
    
    var blogid:Int?
    var toUser:User?
    
    var commentSuccess:((_ comment:Comment)->Void)?
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    func setupUI() {
        
        
        IQKeyboardManager.shared.keyboardDistanceFromTextField = 40
        
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(closeAction)))
        
        self.view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        
        
        
        if let user = toUser,let name = user.nickname {
            
            commetTF.placeholder = "回复\(name)："
        } else {
            
            commetTF.placeholder = "写评论"
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        
        super.viewDidAppear(animated)
        
        self.commetTF.becomeFirstResponder()
    }
    
    func show(_ with:UIViewController) {
        
        self.modalPresentationStyle = .overCurrentContext
        
        with.present(self, animated: false, completion: nil)
        
        
    }
    
    @objc func closeAction() {
        
        self.commetTF.resignFirstResponder()
        
        DispatchQueue.main.after(0.25) {
            [weak self] in
            guard let `self` = self else { return }
            
            self.dismiss(animated: false, completion: nil)
        }
    }

    @IBAction func commentAction(_ sender: Any) {
        
        guard let bid = blogid else {
            
            showToast("初始化错误，请稍后再试")
            return
        }
        
        guard let remark = commetTF.text,remark.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).count > 0 else {
            
            showToast("请输入评论内容")
            return
        }
        
        NetAPI.comment(bid: bid, toUid: toUser?._id, remark: remark).request {
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            if let msg = errmsg {
                
                self.showToast(msg)
                return
            }
            
            let comment = Comment()
            
            comment.comment_user_info = AppManager.share.user
            comment.to_user_info = self.toUser
            comment.remark = remark
            
            self.commentSuccess?(comment)
            
            self.closeAction()
        }
    }
    
}
